<template>
  <div class="chat-sidebar">

    
    <div class="conversation-list">
      <!-- 按时间分组显示会话 -->
      <template v-for="(group, groupName) in groupedConversations" :key="groupName">
        <div class="conversation-group" v-if="group.length > 0">
          <div class="group-header">{{ groupName }}</div>
          <div 
            v-for="conversation in group" 
            :key="conversation.id"
            :class="['conversation-item', { active: activeId === conversation.id }]"
            @click="$emit('select', conversation.id)"
          >
            <div class="conversation-info">
              <div class="conversation-title">
                {{ getConversationTitle(conversation) }}
              </div>
              <div class="conversation-preview">
                {{ getConversationPreview(conversation) }}
              </div>
            </div>
            <button 
              @click.stop="confirmDelete(conversation.id)" 
              class="delete-btn"
              title="删除会话"
            >
            <Icon icon="mdi:trash-can-outline" width="20" height="20" />

            </button>
          </div>
        </div>
      </template>
      <div v-if="Object.keys(conversations).length === 0" class="empty-state">
        没有会话记录，点击"新建会话"开始聊天。
      </div>
    </div>
  </div>
</template>

<script setup>
import { Icon } from '@iconify/vue'
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
const props = defineProps({
  conversations: {
    type: Object,
    default: () => ({})
  },
  activeId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['select', 'create', 'delete'])

// 根据时间对会话分组
const groupedConversations = computed(() => {
  // 使用 dayjs 计算时间界限点
  const today = dayjs().startOf('day');
  const yesterday = dayjs().subtract(1, 'day').startOf('day');
  const lastWeek = dayjs().subtract(7, 'day').startOf('day');
  
  // 分组结构
  const groups = {
    '今天': [],
    '昨天': [],
    '前7天': [],
    '更早': []
  }
  
  // 将对象转为数组以便排序
  const conversationArray = Object.entries(props.conversations).map(([id, conversation]) => {
    // 获取时间戳，优先使用 update_at，其次是 create_at，最后使用当前时间
    let timestamp;
    if (conversation.updated_at) {
      timestamp = dayjs(conversation.created_at*1000);
    } else if (conversation.created_at) {
      timestamp = dayjs(conversation.updated_at*1000);
    } else {
      timestamp = dayjs();
    }
    
    // console.log("%c Line:87 🥒 timestamp", "color:#6ec1c2", conversation.created_at, timestamp.format('YYYY-MM-DD HH:mm'),timestamp.isBefore(today),timestamp.isAfter(today));
    return {
      id,
      ...conversation,
      timestamp
    }
  });
  
  // 按最后更新时间排序（降序）
  conversationArray.sort((a, b) => b.timestamp.valueOf() - a.timestamp.valueOf());
  
  // 分组
  conversationArray.forEach(conversation => {
    const timestamp = conversation.timestamp;
    
    if (timestamp.isAfter(today) || timestamp.isSame(today)) {
      groups['今天'].push(conversation);
    } else if (timestamp.isAfter(yesterday) || timestamp.isSame(yesterday)) {
      groups['昨天'].push(conversation);
    } else if (timestamp.isAfter(lastWeek) || timestamp.isSame(lastWeek)) {
      groups['前7天'].push(conversation);
    } else {
      groups['更早'].push(conversation);
    }
  });
  
  return groups;
});
// 获取会话标题（优先使用服务端返回的name，否则使用第一条用户消息）
const getConversationTitle = (conversation) => {
  // 优先使用服务端返回的name
  if (conversation.name) {
    return conversation.name;
  }
  
  // 如果没有消息或消息数组为空
  if (!conversation.messages || conversation.messages.length === 0) {
    return '新的会话';
  }
  
  // 尝试找到第一条用户消息
  const firstUserMessage = conversation.messages.find(msg => msg.sender === 'user');
  
  if (firstUserMessage) {
    // 截取用户消息前20个字符作为标题
    const title = firstUserMessage.text.trim().substring(0, 20);
    return title + (firstUserMessage.text.length > 20 ? '...' : '');
  }
  
  return '新的会话';
}

// 获取会话预览（最后一条消息）
const getConversationPreview = (conversation) => {
  // 如果服务端返回了简介，使用简介
  if (conversation.introduction) {
    const preview = conversation.introduction.trim().substring(0, 30);
    return preview + (conversation.introduction.length > 30 ? '...' : '');
  }
  
  // 如果没有消息或消息数组为空
  if (!conversation.messages || conversation.messages.length === 0) {
    return '还没有消息';
  }
  
  // 获取最后一条消息
  const lastMessage = conversation.messages[conversation.messages.length - 1];
  
  // 截取最后一条消息前30个字符作为预览
  const preview = lastMessage.text.trim().substring(0, 30);
  return preview + (lastMessage.text.length > 30 ? '...' : '');
}

// 确认删除
const confirmDelete = (id) => {
  if (confirm('确定要删除这个会话吗？')) {
    emit('delete', id);
  }
}
</script>

<style scoped>
.chat-sidebar {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f7f7f7;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e6e6e6;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0 0 12px 0;
}

.new-chat-btn {
  width: 100%;
  padding: 8px 12px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

.new-chat-btn:hover {
  background-color: #40a9ff;
}

.new-chat-btn span {
  margin-right: 6px;
  font-weight: bold;
}

.conversation-list {
  flex-grow: 1;
  overflow-y: auto;
  padding: 8px;
}

/* 会话分组样式 */
.conversation-group {
  margin-bottom: 16px;
}

.group-header {
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 500;
  color: #666;
  text-transform: uppercase;
  background-color: #f7f7f7;
  border-radius: 4px;
  margin-bottom: 4px;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.conversation-item:hover {
  background-color: #e6f7ff;
}

.conversation-item.active {
  background-color: #e6f7ff;
  border-left: 3px solid #1890ff;
}

.conversation-info {
  flex-grow: 1;
  overflow: hidden;
}

.conversation-title {
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-preview {
  font-size: 12px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.delete-btn {
  opacity: 0.3;
  border: none;
  background: none;
  cursor: pointer;
  padding: 4px;
  transition: opacity 0.2s;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.empty-state {
  padding: 20px;
  text-align: center;
  color: #999;
  font-size: 14px;
}
</style>